//
//  ForgetPasswordViewController.m
//  TeacherNet
//
//  Created by slz on 2018/1/5.
//  Copyright © 2018年 bnsr. All rights reserved.
//

#import "ForgetPasswordViewController.h"
#define kTextFiledBoderColor [UIColor colorWithRGB:0xb5b6b8]

@interface ForgetPasswordViewController ()

@end

@implementation ForgetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showNavigationBar = YES;
    UIBarButtonItem * backItem = [UIBarButtonItem itemWithImage:@"back_icon" selectImage:@"" addTarget:self andAction:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = backItem;
    [self setControllerTitle:@"忘记密码"];
    [self creatViews];
    // Do any additional setup after loading the view.
}

- (void)creatViews
{
    CGFloat  textFieldWidth = (kScreenWidth - 60) * .5;
    
    _textFiled1 = [[TTTextFiled alloc]initWithPlaceholder:@"手机号" andLeftImageName:@"user_login_useraccount"];
    _textFiled1.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:_textFiled1];
    [_textFiled1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.top.mas_equalTo(self.view.mas_top).offset(20);
        make.height.mas_equalTo(40);
    }];
    
    _textFiled2 = [[TTTextFiled alloc]initWithPlaceholder:@"验证码" andLeftImageName:@"user_login_password"];
    _textFiled2.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:_textFiled2];
    [_textFiled2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.width.mas_equalTo(textFieldWidth);
        make.top.mas_equalTo(_textFiled1.mas_bottom).offset(30);
        make.height.mas_equalTo(40);
    }];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(timeAction)];
    _getMessageButton = [UILabel new];
    _getMessageButton.text = @"获取短信验证码";
    _getMessageButton.textAlignment = NSTextAlignmentCenter;
    _getMessageButton.fontSize = kFont_Size_Cotent_Nomal;
    _getMessageButton.layer.borderWidth = 1.5;
    _getMessageButton.layer.borderColor = kTextFiledBoderColor.CGColor;
    _getMessageButton.userInteractionEnabled = YES;
    [_getMessageButton addGestureRecognizer:tap];
    _getMessageButton.backgroundColor = [UIColor colorWithRGB:0xF5F5F6];
    _getMessageButton.textColor = [UIColor colorWithRGB:0x919394];
    [self.view addSubview:_getMessageButton];
    [_getMessageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(textFieldWidth, 40));
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.top.mas_equalTo(_textFiled2.mas_top);
    }];
    
    _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _indicatorView.hidesWhenStopped = YES;
    [_getMessageButton addSubview:_indicatorView];
    [_indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(_getMessageButton);
    }];
    
    _textFiled3 = [[TTTextFiled alloc]initWithPlaceholder:@"新密码" andLeftImageName:@"user_login_password"];
    _textFiled3.keyboardType = UIKeyboardTypePhonePad;
    _textFiled3.secureTextEntry = YES;
    [self.view addSubview:_textFiled3];
    [_textFiled3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.top.mas_equalTo(_textFiled2.mas_bottom).offset(30);
        make.height.mas_equalTo(40);
    }];
    
    _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginButton.backgroundColor = kLoginGreenColor;
    [_loginButton setTitle:@"提    交" forState:UIControlStateNormal];
    [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _loginButton.titleLabel.fontSize = 16;
    [_loginButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginButton];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(_textFiled1);
        make.top.mas_equalTo(_textFiled3.mas_bottom).offset(30);
        make.height.mas_equalTo(40);
    }];

}


- (void)submitAction{
    [self.view endEditing:YES];
    NSString * phoneString = _textFiled1.text;
    NSString * message = _textFiled2.text;
    NSString * password = _textFiled3.text;
    if (![self validateNumber:phoneString]){
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码~"];
        return;
    }
    if (!message || message.length == 0){
        [SVProgressHUD showErrorWithStatus:@"请输入验证码~"];
        return;
    }
    if (!password || password.length < 6 || password.length > 16){
        [SVProgressHUD showErrorWithStatus:@"请输入6-16位密码"];
        return;
    }
    [BaseHttpTool get:kAPI_REST_PASSWORD params:@{@"yzm":message,@"phone":phoneString,@"password":password} success:^(id responseObj) {
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        NSInteger flag = [json intValueForKey:@"flag"];
        if (flag == 1){
            [self.view showTip:@"修改成功,请返回登录" completion:nil];
        }else
        {
            NSString * errorString;
            switch (flag) {
                case 2:
                    errorString = @"验证码超时";
                    break;
                    case 3:
                    errorString = @"验证码错误";
                    break;
                    case 4:
                    errorString = @"用户不存在";
                    break;
                default:
                    errorString = @"修改失败";
                    break;
            }
            [SVProgressHUD showErrorWithStatus:errorString];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}

- (void)timeAction{
    NSString * phoneString = _textFiled1.text;
    if (![self validateNumber:phoneString]){
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码~"];
        return;
    }
    _getMessageButton.text = @"";
    [_indicatorView startAnimating];
    _getMessageButton.exclusiveTouch = YES;
    _getMessageButton.userInteractionEnabled = NO;
    [BaseHttpTool get:kAPI_APP_MESSAGE_VALIDE params:@{@"phone":phoneString} success:^(id responseObj) {
        [_indicatorView stopAnimating];
        NSString * result = [responseObj stringValueForKey:@"status"];
        if ([result isEqualToString:@"0"]){
            [self timeStart];
        }else{
            [SVProgressHUD showErrorWithStatus:@"获取验证码失败~"];
            _getMessageButton.text = @"获取短信验证码";
            self.getMessageButton.userInteractionEnabled = YES;
        }
    } failure:^(NSError *error) {
        _getMessageButton.text = @"获取短信验证码";
        [_indicatorView stopAnimating];
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        self.getMessageButton.userInteractionEnabled = YES;
    }];
}

- (BOOL)validateNumber:(NSString *)textString
{
    if (textString.length != 11){
        return NO;
    }
    NSString* number=@"^[0-9]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}

- (void)timeStart{
    __block int time = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (time < 1){
            dispatch_source_cancel(_timer);// gcd timer中必须要有 cancle 这个timer的代码 否则代码将无法执行。
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * defaultTimeString = @"获取验证码";
                self.getMessageButton.text = defaultTimeString;
                self.getMessageButton.userInteractionEnabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                time--;
                NSString *timeString = [NSString stringWithFormat:@"%d",time];
                self.getMessageButton.text = timeString;
            });
        }
    });
    dispatch_resume(_timer);
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
